<template>
	<view class="content">
		<!-- <view>蓝牙设备</view> -->
		<view style="padding: 10px;">
			设备名称:{{name}}
		</view>
		<view style="padding: 10px;">
			DeviceID: {{deviceId}}
		</view>
		<view style="padding: 10px;">
			<button type="primary" @tap="bindViewTapimg" :disabled='btn_disabled'>打印标签 </button>
		</view>
		<view class="index-server-content">
			<!-- <view class="section__title">MTU包大小 </view>
			<view class="inputView">
				<input class="input" placeholder="请输入包大小" auto-focus maxlength="3" @input="MTUInput" :value="MTUSize" />
			</view> -->
			<!-- <button type="primary" @tap="bindViewTap1" :disabled='btn_disabled'> 打印 </button>
			<button type="primary" @tap="bindViewTap2" :disabled='btn_disabled'> 打印二维码 </button> -->
			<view style="margin-top:30rpx;">
				<canvas
				 v-for="(item,index) in filePathArray" :key="index" 
				 :style="{width: canvasWidth +'px', height: canvasHeight +'px',margin:'0 auto'}" 
				:canvas-id="'firstCanvas'+index" 
				 />	
			</view>
		</view>

		
	</view>
</template>

<script>
	const app = getApp()
	var util = require('../../utils/util.js');
	var gbk = require('../../utils/printUtil-GBK.js');
	var pako = require('pako');
	import * as zksdk from '../../utils/bluetoolth';
	var recArrayBuff = new ArrayBuffer(256);
	var recLen = 0;
	const errMsg = {
		10000: '未初始化蓝牙模块',
		10001: '蓝牙未打开',
		10002: '没有找到指定设备',
		10003: '连接失败',
		10004: '没有找到指定服务',
		10005: '没有找到指定特征值',
		10006: '当前连接已断开',
		10007: '当前特征值不支持此操作',
		10008: '系统上报异常',
		10009: '系统版本低于 4.3 不支持BLE'
	};

	function crc32fun(buf, offset, len) {
		const crcTable = new Uint32Array([
			0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535,
			0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD,
			0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D,
			0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
			0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4,
			0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C,
			0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC,
			0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
			0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB,
			0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,
			0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB,
			0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
			0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA,
			0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE,
			0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A,
			0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
			0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409,
			0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81,
			0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739,
			0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
			0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268,
			0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0,
			0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8,
			0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
			0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF,
			0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703,
			0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7,
			0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
			0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE,
			0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
			0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6,
			0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
			0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D,
			0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5,
			0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605,
			0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
			0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
		]);

		let crc = -1;
		for (let i = offset; i < len + offset; i++) {
			crc = (crc >>> 8) ^ crcTable[(crc ^ buf[i]) & 0xFF];
		}
		return (crc ^ (-1));
	};

	function myGzip(bytes) {
		var gzipData = pako.gzip(new Uint8Array(bytes));
		gzipData[8] = 0x04;
		gzipData[9] = 0x00;
		var crc = crc32fun(gzipData, 8, gzipData.byteLength - 8 - 4)
		gzipData[4] = ((gzipData.byteLength >> 0) & 0xFF);
		gzipData[5] = ((gzipData.byteLength >> 8) & 0xFF);
		gzipData[6] = ((gzipData.byteLength >> 16) & 0xFF);
		gzipData[7] = ((gzipData.byteLength >> 24) & 0xFF);
		gzipData[gzipData.byteLength - 4] = ((crc >> 0) & 0xFF);
		gzipData[gzipData.byteLength - 3] = ((crc >> 8) & 0xFF);
		gzipData[gzipData.byteLength - 2] = ((crc >> 16) & 0xFF);
		gzipData[gzipData.byteLength - 1] = ((crc >> 24) & 0xFF);
		let bufferGzip = new ArrayBuffer(gzipData.length);
		let dv = new DataView(bufferGzip);
		for (var i = 0; i < bufferGzip.byteLength; i++) {
			dv.setUint8(i, gzipData[i]);
		}
		//console.log(bufferGzip);
		return bufferGzip;
	}
	export default {
		components: {},
		data() {
			return {
				deviceId: '',
				name: '',
				services: [],
				serviceId: '',
				writeId: '',
				readId: '',
				SERVERMAINSERVER: '',
				WRITEMAINSERVER: '',
				btn_disabled: true,
				result: '',
				State: '',
				Dev_mac: '',
				showViewWiFi: false,
				showViewLAN: false,
				WiFiAPName: ' ',
				WiFiAPGetFlg: false,
				LANIP: '',
				LANMask: '',
				LANGateWay: '',
				MTUSize: 20,
				LANIPValue: '',
				LANMaskValue: '',
				LANGateWayValue: '',
				canvasWidth: 800,
				canvasHeight: 400,
				filePathArray:[],
				barSizeType:'',
				selIds : '',
				prtQtys : ''
			}
		},

		onUnload: function() {
			zksdk.closeBLEConnection(this.deviceId);
			zksdk.stopBlueDevicesDiscovery();
		},
		onLoad(opt) {
			
			this.selIds = opt.selIds
			this.prtQtys = opt.prtQtys
			this.getdictData()
			
			
			
			var that = this;
			//var serv_id = '0000FFF0-0000-1000-8000-00805F9B34FB'
			console.log("bluetooththrsec onLoad");
			// 生命周期函数--监听页面加载
			showViewWiFi: (opt.showViewWiFi == "true" ? true : false)
			showViewLAN: (opt.showViewLAN == "true" ? true : false)

			var LANIP = wx.getStorageSync('LANIP');
			var LANMask = wx.getStorageSync('LANMask');
			var LANGateWay = wx.getStorageSync('LANGateWay');
			that.LANIPValue = LANIP;
			that.LANMaskValue = LANMask;
			that.LANGateWayValue = LANGateWay;
			that.LANIP = LANIP;
			that.LANMask = LANMask;
			that.LANGateWay = LANGateWay;

			var MTUSize = wx.getStorageSync('MTUSize');
			if (MTUSize != undefined) {
				that.MTUSize = MTUSize;
				that.MTUSize = MTUSize;
			} else {
				that.MTUSize = 20;
				that.MTUSize = 20;
			}
			console.log('deviceId=' + opt.deviceId);
			console.log('name=' + opt.name);
			that.btn_disabled = true;
			console.log('Disable button');
			that.deviceId = opt.deviceId
			that.name = opt.name
			// that.setData({
			// 	deviceId: opt.deviceId,
			// 	name: opt.name
			// });
			// 监听设备的连接状态
			wx.onBLEConnectionStateChange(function(res) {
				console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
			})

			zksdk.createBLEConnection(that.deviceId, this.onConnectSuccess, this.onConnectFail);

		},
		methods: {
			getdictData(){
				this.$u.api.dictListData({dictType: 'bar_size_type1'}).then(res => {
					console.log(res,'res===')
					this.barSizeType = res[0]['dictValue']
					console.log(res,'res===',this.barSizeType)
					this.getFilePathArray();
				})	
			},
			getFilePathArray(){
				const params = {
					selIds: this.selIds,
					prtQtys: this.prtQtys,
					rsPics:1,
					barType: this.vuex_config.MoNotify,
					barSizeType: this.barSizeType,
				}
				this.$u.api.mf.printSnNumber(params).then(res=>{	
					if(res.result == 'true'){
						this.filePathArray = res.pdfUrl
						this.renderCanvas()
					}else{
						this.$refs.jsError.showError('',res.message,'error');
					}
				})
			},
			renderCanvas() {
				// 根据 filePathArray 图片路径数组加载图片
				let that = this
				console.log(that.filePathArray,'that.filePathArray===')
				for (let i = 0; i < that.filePathArray.length; i++) {
					let filePath = this.vuex_config.baseUrl + that.filePathArray[i]
					console.log(filePath,'filePath')
					const firstCanvas = uni.createCanvasContext('firstCanvas'+ i);
					
					uni.downloadFile({
					  url: filePath, // 图片的URL
					  success: function (res) {
					    const tempFilePath = res.tempFilePath;
					    // 如果下载成功，则尝试保存图片到相册
					    if (res.statusCode === 200) {
					      uni.getImageInfo({
					      	src: tempFilePath,
					      	success(res) {
					      		console.log(res.width + "--" + res.height)
					      		that.canvasWidth = res.width * 0.8
					      		that.canvasHeight = res.height * 0.76
					      		console.log(res, that.canvasWidth, that.canvasHeight)
					      		firstCanvas.drawImage(tempFilePath, -50, -20, that.canvasWidth, that.canvasHeight);
					      		firstCanvas.draw();
					      		that.$forceUpdate()
					      	},
					      	fail(res) {
					      		// console.log(res)
					      		that.$refs.jsError.showError('',res.errMsg,'error');
					      	}
					      })
					    } else {
					      console.error('下载失败', res);
					      uni.showToast({
					        title: '下载失败',
					        icon: 'none'
					      });
					    }
					  },
					  fail: function (err) {
					    console.error('下载失败', err);
					    uni.showToast({
					      title: '下载失败',
					      icon: 'none'
					    });
					  }
					});
					
					
					
					
				
				}
				
			},

			//---连接成功----
			onConnectSuccess(res) {
				var that = this;
				console.log('onConnectSuccess', res);
				zksdk.getBLEDeviceServices(that.deviceId, this.onGetServicesSuccess, this.onGetServicesFail);
			},
			//---连接失败----
			onConnectFail(res) {
				console.log('onConnectFail', res);
			},
			//---Services获取成功----
			onGetServicesSuccess(res) {
				var that = this;
				console.log('onGetServicesSuccess', res);
				this.services = res.serviceId;
				zksdk.getDeviceCharacteristics(that.deviceId, that.services, this.onGetCharacterSuccess, this
					.onGetCharacterFail);
			},
			//---Services获取失败----
			onGetServicesFail(res) {
				console.log('onGetServicesFail', res);
			},
			//---Characteristics获取成功----
			onGetCharacterSuccess(res) {
				console.log('onGetCharacterSuccess servid ', res.serviceId);
				console.log('write character ', res.writeId);
				console.log('read character ', res.readId);
				this.serviceId = res.serviceId
				this.writeId = res.writeId
				this.readId = res.readId
				this.btn_disabled = false
				// this.setData({
				// 	serviceId: res.serviceId,
				// 	writeId: res.writeId,
				// 	readId: res.readId,
				// });
				// this.setData({
				// 	btn_disabled: false
				// });
				console.log('Enable button');
				//---停止扫描蓝牙设备---------
				zksdk.stopBlueDevicesDiscovery();
				//-----打开状态通知功能------
				const opt = {
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId: this.readId,
				};
				zksdk.onGetBLECharacteristicValueChange(opt, this.onGetBLEValueChange);
			},
			//---Characteristics获取失败----
			onGetCharacterFail(res) {
				console.log('onGetCharacterFail', res);
			},

			//------Characteristic信息变化回调-------
			onGetBLEValueChange: function(res) {
				var that = this;
				console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
				console.log(util.ab2hex(res.value))
				//if (res.characteristicId == `0000FFF1-0000-1000-8000-00805F9B34FB`)
				{
					var view1 = new DataView(res.value);
					//console.log(res.value.byteLength);
					//console.log(view1.getUint8(0));
					//console.log(view1.getUint8(2));
					if (res.value.byteLength >= 4 && view1.getUint8(0) == 0x1d && view1.getUint8(1) == 0x99) {
						let strSta = " ";
						if (view1.getUint8(2) == 0) strSta = "正常";
						if (view1.getUint8(2) & 0x01) strSta = strSta + ' 缺纸';
						if (view1.getUint8(2) & 0x02) strSta = strSta + ' 开盖';
						if (view1.getUint8(2) & 0x04) strSta = strSta + ' 打印头过热';
						if (view1.getUint8(2) & 0x08) strSta = strSta + ' 定位失败';
						if (view1.getUint8(2) & 0x10) strSta = strSta + ' 低电';
						if (view1.getUint8(2) & 0x20) strSta = strSta + ' 正在打印';
						that.State = strSta
					} else if (res.value.byteLength >= 9 && view1.getUint8(0) == 0x20 && view1.getUint8(1) == 0x06) {
						//---MAC地址获取----             
						let buffer = new ArrayBuffer(6)
						let dataView = new DataView(buffer)
						for (var i = 0; i < 6; i++) dataView.setUint8(i, view1.getUint8(3 + i));

						let dev_mac = buffer.join(":");
						that.Dev_mac = dev_mac;
						console.log('mac:' + dev_mac);
					} else if (res.value.byteLength >= 3 && view1.getUint8(0) == 0x1D && view1.getUint8(1) == 0x49 &&
						view1.getUint8(2) == 0x4A) {
						let len = res.value.byteLength
						let dataView = new DataView(recArrayBuff)
						recLen = 0;
						for (var i = 0; i < len - 3; i++) dataView.setUint8(i, view1.getUint8(3 + i));
						recLen = len - 3;
					} else if (res.value.byteLength >= 3 && view1.getUint8(0) == 0x30 && view1.getUint8(1) == 0x00 &&
						view1.getUint8(1) == 0x00) {
						console.log('Resp OK');
					} else {
						if (that.WiFiAPGetFlg) {
							let len = res.value.byteLength;
							let dataView = new DataView(recArrayBuff)
							for (var i = 0; i < len; i++) dataView.setUint8(i + recLen, view1.getUint8(i));
							recLen += len
							if (view1.getUint8(len - 1) == 0 || view1.getUint8(len - 1) == 0x0A) {
								that.WiFiAPName = util.Utf8ArrayToStr(new Uint8Array(recArrayBuff));
								console.log(that.WiFiAPName)
								that.WiFiAPName = that.WiFiAPName
								recLen = 0;
							}
							that.timer = setTimeout(
								function() {
									// TODO 你需要执行的任务
									console.log('startTimer  500毫秒后执行一次任务')
									var Scan = util.Utf8ArrayToStr(new Uint8Array(recArrayBuff));
									console.log(Scan)
									that.WiFiAPName = that.WiFiAPName
									recLen = 0;
									that.WiFiAPGetFlg = false;
								}, 500);
						} else {
							var Scan = util.Utf8ArrayToStr(new Uint8Array(res.value));
							console.log(Scan)
							that.State = Scan
							this.bindViewTap1(null, Scan);
						}
					}
				}
			},

			
			//---数据全部发送成功回调----
			onSendSuccess: function() {
				console.log("onSendSuccess");
			},

			MTUInput: function(e) {
				var that = this;
				that.MTUSize = e.detail.value
				that.MTUSize = e.detail.value;
				wx.setStorageSync('MTUSize', e.detail.value);
				console.log('that.MTUSize:', that.MTUSize)
			},

		


			//---获取设备传统蓝牙MAC地址----
			GetDevBTMac: function() {
				var that = this;
				var a1 = that.GetDevicePar("BLUETOOTH_ADDR", 3);
				//console.log('a1', a1);
				let buffer = new ArrayBuffer(a1.byteLength);
				var vb = new Uint8Array(buffer, 0);
				var vblen = 0;
				let data = new Uint8Array(a1, 0, a1.byteLength);
				var datalen = 20;
				if (app.globalData.platform == 'ios') {
					console.log('platform:', app.globalData.platform)
					datalen = 120;
				}
				for (var i = 0; i < a1.byteLength; i++) vb[vblen++] = data[i];
				console.log('buffer:', buffer);

				const opt = {
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId: this.writeId,
					value: buffer,
					lasterSuccess: this.onSendSuccess,
					onceLength: datalen
				};
				//const opt = { deviceId: this.deviceId, ...this.character };
				zksdk.sendDataToDevice(opt);
			},
			//----打印二维码-------
			bindViewTap2: function() {
				var that = this;
				let strCmd1 = zksdk.CreatCPCLPage(576, 300, 1);
				strCmd1 += zksdk.addCPCLLocation(2);
				let strCmd2 = zksdk.addCPCLQRCode(10, 10, 'M', 2, 5, "中文二维码测试");
				let strCmd3 = zksdk.addCPCLText(10, 150, '24', '0', 0, "中文二维码测试");
				strCmd3 += zksdk.addCPCLPrint();
				var byte1 = gbk.strToGBKByte(strCmd1);
				var byte2 = gbk.stringToArrayBuffer(strCmd2);
				var byte3 = gbk.strToGBKByte(strCmd3);
				var bytes = new ArrayBuffer(byte1.byteLength + byte2.byteLength + byte3.byteLength);
				var dv = new DataView(bytes);
				var dv1 = new DataView(byte1);
				var dv2 = new DataView(byte2);
				var dv3 = new DataView(byte3);
				for (var i = 0; i < byte1.byteLength; i++) {
					dv.setInt8(i, dv1.getInt8(i));
				}
				for (var i = 0; i < byte2.byteLength; i++) {
					dv.setInt8(byte1.byteLength + i, dv2.getInt8(i));
				}
				for (var i = 0; i < byte3.byteLength; i++) {
					dv.setInt8(byte1.byteLength + byte2.byteLength + i, dv3.getInt8(i));
				}

				// bytes = pako.myGzip(bytes);
				bytes = pako.gzip(bytes);
				console.log(bytes)

				var datalen = 20;
				if (app.globalData.platform == 'ios') {
					console.log('platform:', app.globalData.platform)
					datalen = 120;
				}

				const opt = {
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId: this.writeId,
					value: bytes,
					lasterSuccess: this.onSendSuccess,
					onceLength: datalen
				};
				//const opt = { deviceId: this.deviceId, ...this.character };
				zksdk.sendDataToDevice(opt);
			},
			bindViewTapimg: async function() {
				
				let that = this
				// 循环打印
				const printPromises = this.filePathArray.map((filePath, index) => {
					return new Promise((resolve, reject) => {
					uni.canvasGetImageData({
						canvasId: 'firstCanvas' + index,
						x: 0,
						y: 0,
						width: this.canvasWidth, // 确保这些值在调用前已被正确设置
						height: this.canvasHeight,
						success: (res) => {
							console.log('ImageData success:', res);
							resolve(res); // 将结果解析为 Promise 的值
						},
						fail: (res) => {
							console.error('ImageData fail:', res);
							this.$refs.jsError.showError('', res.errMsg, 'error');
							reject(res.errMsg); // 将错误信息作为 Promise 的拒绝理由
						}
					});
					});
				});
				
				const imageDatas = await Promise.all(printPromises);
				
				imageDatas.forEach((item,index)=>{
					console.log(item,'=======================666');
					setTimeout(() => {
						const w = item.width;
						const h = item.height;
						//获取画布里的图片数据
						uni.canvasGetImageData({
							canvasId: 'firstCanvas'+index,
							x: 0,
							y: 0,
							width: w,
							height: h,
							success: (res) => {
								console.log(res,
									'canvasGetImageData===='
									);
								const pix = res
									.data;
								const opt = {
									deviceId: this
										.deviceId,
									serviceId: this
										.serviceId,
									characteristicId: this
										.writeId,
									lasterSuccess: this
										.onSendSuccess
								};
								//----ESC指令打印----
								/*
								const sendImageinfo = zksdk.overwriteImageData({
								  imageData: pix,
								  width: w,
								  height: h,
								  threshold: 190,
								});
								console.log(sendImageinfo);
								//打印图片
								zksdk.printImage(opt, sendImageinfo);
								*/
								/*const sendImageinfo = zksdk.overwriteImageData2({
								  imageData: pix,
								  width: w,
								  height: h,
								  threshold: 190,
								});
								console.log(sendImageinfo);*/
								
								/*let strImg=zksdk.addCPCLImageCmd(10,10, {
								  imageData: pix,  width: w, height: h, threshold: 190,
								});*/
								var d1 =
									new Date();
								var n1 = d1
									.getTime();
								console.log(
									"start time:",
									n1);
								
								let strCmd = zksdk
									.CreatCPCLPage(
										576, h +
										60, 1);
								strCmd += zksdk
									.addCPCLImageCmd(
										10, 10, {
											imageData: pix,
											width: w,
											height: h,
											threshold: 200,
										});
								strCmd += zksdk
									.addCPCLPrint();
								
								let buffer = gbk
									.strToGBKByte(
										strCmd);
								buffer = myGzip(
									buffer);
								console.log(buffer,
									'buffer1111====')
								console.log(uni
									.getSystemInfoSync(),
									'app====')
								var datalen = 20;
								if (uni.getSystemInfoSync()
									.osName ==
									'ios') {
									console.log(
										'platform:',
										uni
										.getSystemInfoSync()
										.osName
									)
									datalen = 120;
								}
								const opt2 = {
									deviceId: this
										.deviceId,
									serviceId: this
										.serviceId,
									characteristicId: this
										.writeId,
									value: buffer,
									lasterSuccess: this
										.onSendSuccess,
									onceLength: datalen
								};
								console.log(
									strCmd);
								
								var d2 =
									new Date();
								var n2 = d2
									.getTime();
								console.log(
									"end time1:",
									n2);
								var usedTime1 =
									n2 -
									n1; //两个时间戳相差的毫秒数
								console.log(
									"Delta time1:",
									usedTime1);
								
								zksdk
									.sendDataToDevice(
										opt2);
								
								var d3 =
									new Date();
								var n3 = d3
									.getTime();
								console.log(
									"end time1:",
									n3);
								var usedTime2 =
									n3 -
									n2; //两个时间戳相差的毫秒数
								console.log(
									"Delta time2:",
									usedTime2);
							},
						});
					}, 100);
					
				})
			},
			//----打印图片-------
			bindViewTap3: function() {
				var that = this;

				const ctx = uni.createCanvasContext('secondCanvas');
				//选择一张图片
				uni.chooseImage({
					success: (res) => {
						const temppath = res.tempFilePaths[0];
						//获取图片的宽高信息
						uni.getImageInfo({
							src: temppath,
							success: (res) => {
								const w = res.width * 0.8;
								const h = res.height * 0.76;
								this.canvasWidth = w
								this.canvasHeight = h
								console.log(this.canvasWidth, this.canvasHeight, '宽高');
								console.log(w, h);
								// this.setData({
								// 		canvasHeight: h,
								// 		canvasWidth: w,
								// 	},
								// () => {
								//canvas 画一张图片
								ctx.drawImage(temppath, -50, -20, w, h);
								ctx.draw();
								setTimeout(() => {
									//获取画布里的图片数据
									uni.canvasGetImageData({
										canvasId: 'secondCanvas',
										x: 0,
										y: 0,
										width: w,
										height: h,
										success: (res) => {
											console.log(res,
												'canvasGetImageData===='
												);
											const pix = res
												.data;
											const opt = {
												deviceId: this
													.deviceId,
												serviceId: this
													.serviceId,
												characteristicId: this
													.writeId,
												lasterSuccess: this
													.onSendSuccess
											};
											//----ESC指令打印----
											/*
											const sendImageinfo = zksdk.overwriteImageData({
											  imageData: pix,
											  width: w,
											  height: h,
											  threshold: 190,
											});
											console.log(sendImageinfo);
											//打印图片
											zksdk.printImage(opt, sendImageinfo);
											*/
											/*const sendImageinfo = zksdk.overwriteImageData2({
											  imageData: pix,
											  width: w,
											  height: h,
											  threshold: 190,
											});
											console.log(sendImageinfo);*/

											/*let strImg=zksdk.addCPCLImageCmd(10,10, {
											  imageData: pix,  width: w, height: h, threshold: 190,
											});*/
											var d1 =
												new Date();
											var n1 = d1
												.getTime();
											console.log(
												"start time:",
												n1);

											let strCmd = zksdk
												.CreatCPCLPage(
													576, h +
													60, 1);
											strCmd += zksdk
												.addCPCLImageCmd(
													10, 10, {
														imageData: pix,
														width: w,
														height: h,
														threshold: 200,
													});
											strCmd += zksdk
												.addCPCLPrint();

											let buffer = gbk
												.strToGBKByte(
													strCmd);
											buffer = myGzip(
												buffer);
											console.log(buffer,
												'buffer1111====')
											console.log(uni
												.getSystemInfoSync(),
												'app====')
											var datalen = 20;
											if (uni.getSystemInfoSync()
												.osName ==
												'ios') {
												console.log(
													'platform:',
													uni
													.getSystemInfoSync()
													.osName
												)
												datalen = 120;
											}
											const opt2 = {
												deviceId: this
													.deviceId,
												serviceId: this
													.serviceId,
												characteristicId: this
													.writeId,
												value: buffer,
												lasterSuccess: this
													.onSendSuccess,
												onceLength: datalen
											};
											console.log(
												strCmd);

											var d2 =
												new Date();
											var n2 = d2
												.getTime();
											console.log(
												"end time1:",
												n2);
											var usedTime1 =
												n2 -
												n1; //两个时间戳相差的毫秒数
											console.log(
												"Delta time1:",
												usedTime1);

											zksdk
												.sendDataToDevice(
													opt2);

											var d3 =
												new Date();
											var n3 = d3
												.getTime();
											console.log(
												"end time1:",
												n3);
											var usedTime2 =
												n3 -
												n2; //两个时间戳相差的毫秒数
											console.log(
												"Delta time2:",
												usedTime2);
										},
									});
								}, 100);
								// },
								// );
							},
						});
					},
				});

			},

			//热点名和密码输入框事件
			WiFiNameInput: function(e) {
				var that = this;
				that.WiFiName = e.detail.value;
				that.WiFiName = e.detail.value;
				console.log('that.WiFiName:', that.WiFiName);
				//console.log(gbk.stringToArrayBuffer(that.WiFiName)); 
				//console.log(util.str2ab(that.WiFiName));
			},
			passWdInput: function(e) {
				var that = this;
				that.WiFiPassword = e.detail.value
				console.log('that.WiFiPassword:', that.WiFiPassword)
			},
			//------参数封装指令------
			SetDevicePar: function(setname, setdata, flg) {
				let data1 = gbk.stringToArrayBuffer(setname); //util.str2ab(setname);
				let data2;
				if (flg == 3) data2 = setdata;
				else data2 = gbk.stringToArrayBuffer(setdata);

				let a = new Uint8Array(data1, 0, data1.byteLength);
				let b = new Uint8Array(data2, 0, data2.byteLength);
				//console.log('a', a)
				//console.log('b', b)
				var blen = b.byteLength;
				if (blen <= 1) blen = 0;

				let buffer = new ArrayBuffer(a.byteLength + blen + 10);
				var vb = new Uint8Array(buffer, 0);
				vb[0] = 0x1F;
				vb[1] = 0x52;
				vb[2] = buffer.byteLength - 4;
				vb[3] = 0;
				vb[4] = 0x30;
				vb[5] = flg;
				vb[6] = a.byteLength;
				vb[7] = 0;
				vb[8] = blen;
				vb[9] = 0;
				for (var i = 0; i < a.length; i++) vb[10 + i] = a[i];
				for (var i = 0; i < blen; i++) vb[10 + i + a.length] = b[i];
				return buffer;
			},
			GetDevicePar: function(Getname, flg) {
				let data = util.str2ab(Getname);
				let a = new Uint8Array(data, 0, data.byteLength);

				let buffer = new ArrayBuffer(a.byteLength + 6);
				var vb = new Uint8Array(buffer, 0);
				vb[0] = 0x1F;
				vb[1] = 0x52;
				vb[2] = buffer.byteLength - 4;
				vb[3] = 0;
				vb[4] = 0x20;
				vb[5] = flg;
				for (var i = 0; i < a.length; i++) vb[6 + i] = a[i];
				return buffer;
			},
			/**
			 * 发送 WiFi参数到设备中
			 */
			btn_SetWiFiPar: function() {
				var that = this;
				console.log('that.deviceId:', that.deviceId, 'Set WiFi Parameter')
				var a1 = that.SetDevicePar("WIFI_CONFIG_SSID", this.WiFiName, 1);
				var a2 = that.SetDevicePar("WIFI_CONFIG_PASSWORD", this.WiFiPassword, 1);
				var a3 = that.SetDevicePar("reg_value_save", "", 18);
				var a4 = that.SetDevicePar("power_reset", "", 2);
				let buffer = new ArrayBuffer(a1.byteLength + a2.byteLength + a3.byteLength + a4.byteLength);
				var vb = new Uint8Array(buffer, 0);
				var vblen = 0;
				let data = new Uint8Array(a1, 0, a1.byteLength);
				for (var i = 0; i < a1.byteLength; i++) vb[vblen++] = data[i];
				data = new Uint8Array(a2, 0, a2.byteLength);
				for (var i = 0; i < a2.byteLength; i++) vb[vblen++] = data[i];
				data = new Uint8Array(a3, 0, a3.byteLength);
				for (var i = 0; i < a3.byteLength; i++) vb[vblen++] = data[i];
				data = new Uint8Array(a4, 0, a4.byteLength);
				for (var i = 0; i < a4.byteLength; i++) vb[vblen++] = data[i];
				//console.log('buffer:', buffer);
				console.log('wifiname:', a1);
				var datalen = 20;
				if (app.globalData.platform == 'ios') {
					console.log('platform:', app.globalData.platform)
					datalen = 120;
				}
				const opt = {
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId: this.writeId,
					value: buffer,
					lasterSuccess: this.onSendSuccess,
					onceLength: datalen
				};
				zksdk.sendDataToDevice(opt);
			},

			//LAN参数输入
			LANIPInput: function(e) {
				var that = this;
				that.LANIPValue = e.detail.value;
				that.LANIP = e.detail.value;
				wx.setStorageSync('LANIP', e.detail.value);
			},
			LANMaskInput: function(e) {
				var that = this;
				that.LANMaskValue = e.detail.value;
				that.LANMask = e.detail.value;
				wx.setStorageSync('LANMask', e.detail.value);
			},
			LANGateWayInput: function(e) {
				var that = this;
				that.LANGateWayValue = e.detail.value
				that.LANGateWay = e.detail.value;
				wx.setStorageSync('LANGateWay', e.detail.value);
			},
			/**
			 * 发送LAN参数到设备中
			 */
			IptoArray: function(IP) {
				var Arr = new ArrayBuffer(4);
				var view1 = new DataView(Arr);
				var result = IP.replace(/\d+\.?/ig, function(a) {
					a = parseInt(a);
					return (a > 15 ? "" : "0") + a.toString(16);
				})
				view1.setUint32(0, parseInt(result, 16));
				console.log(Arr)
				return Arr;
			},
			btn_SetLANPar: function() {
				var that = this;
				console.log('that.deviceId:', that.deviceId, 'Set Lan Parameter')
				var a1 = that.SetDevicePar("LAN_CONFIG_IPADDRESS", that.IptoArray(this.LANIP), 3);
				var a2 = that.SetDevicePar("LAN_CONFIG_NETMASK", that.IptoArray(this.LANMask), 3);
				var a3 = that.SetDevicePar("LAN_CONFIG_GATEWAY", that.IptoArray(this.LANGateWay), 3);
				var a4 = that.SetDevicePar("reg_value_save", "", 18);
				var a5 = that.SetDevicePar("power_reset", "", 2);
				let buffer = new ArrayBuffer(a1.byteLength + a2.byteLength + a3.byteLength + a4.byteLength + a5
					.byteLength);
				var vb = new Uint8Array(buffer, 0);
				var vblen = 0;
				let data = new Uint8Array(a1, 0, a1.byteLength);
				for (var i = 0; i < a1.byteLength; i++) vb[vblen++] = data[i];
				data = new Uint8Array(a2, 0, a2.byteLength);
				for (var i = 0; i < a2.byteLength; i++) vb[vblen++] = data[i];
				data = new Uint8Array(a3, 0, a3.byteLength);
				for (var i = 0; i < a3.byteLength; i++) vb[vblen++] = data[i];
				data = new Uint8Array(a4, 0, a4.byteLength);
				for (var i = 0; i < a4.byteLength; i++) vb[vblen++] = data[i];
				data = new Uint8Array(a5, 0, a5.byteLength);
				for (var i = 0; i < a5.byteLength; i++) vb[vblen++] = data[i];
				//console.log('buffer:', buffer);
				var datalen = 20;
				if (app.globalData.platform == 'ios') {
					console.log('platform:', app.globalData.platform)
					datalen = 120;
				}
				const opt = {
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId: this.writeId,
					value: buffer,
					lasterSuccess: this.onSendSuccess,
					onceLength: datalen
				};
				zksdk.sendDataToDevice(opt);
			},

			onChangeShowWiFi: function() {
				var that = this;
				console.log("onChangeshowViewWiFi=" + that.showViewWiFi);
				that.showViewWiFi = !that.showViewWiFi
			},
			onChangeShowLAN: function() {
				var that = this;
				console.log("onChangeshowViewLAN=" + that.showViewLAN);
				that.showViewLAN = !that.showViewLAN
			},
		}
	}
</script>

<style>
	button {
		width: 300rpx;
		height: 80rpx;
		padding: 10rpx 0;
		color: #000;
		line-height: 50rpx;
		font-size: 32rpx;
		color: #fff;
		background: green;
	}

	button[disabled]:not([type]) {
		background: red;
		color: #fff;
	}

	.index-server-content {
		width: 100%;
		overflow: hidden;
		border-top: 1px solid #e5e5e5;
		border-bottom: 1px solid #e5e5e5;
		margin-top: 30px;
	}

	.section {
		display: flex;
		flex-direction: row;
		margin: 20rpx;
	}

	.section view {
		margin-right: 20rpx;
	}

	.btn-area {
		margin: 20rpx;
	}

	button {
		margin: 10rpx 0;
	}

	.input {
		padding-left: 10px;
		height: 44px;
	}

	.inputView {
		border: 2px solid red;
		border-radius: 40px;
		margin-left: 15px;
		margin-right: 15px;
		margin-top: 15px;
	}

	.hide {
		display: none;
	}

	.show {
		display: block;
	}
</style>